
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Emberjs,Ember-Teach,Ember-Route," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>终止与重试路由跳转 [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        终止与重试路由跳转
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:37.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Route/" rel="tag">Ember-Route</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Teach/" rel="tag">Ember-Teach</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Emberjs/" rel="tag">Emberjs</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 3 分钟</span>
    </header>

    <div class="post-content">
      <p>在路由的转换过程中，Ember路由器会通过回调（<code>beforeModel</code>、<code>model</code>、<code>afterModel</code>、<code>redirect</code>）解析一个<code>transition</code>对象到转换的下一路由中。任何一个回调都可以通过传递过来的<code>transition</code>参数获取<code>transition</code>对象，然后使用这个对象调用<code>transition.abort()</code>方法立即终止路由的转换，如果你的程序保存了这个对象（<code>transition</code>对象）之后你还可以在需要的地方取出来并调用<code>transition.retry()</code>方法激活路由转换这个动作，最终实现路由的转换。</p>
<h3 id="1，通过调用willTransition方法阻止路由转换"><a href="#1，通过调用willTransition方法阻止路由转换" class="headerlink" title="1，通过调用willTransition方法阻止路由转换"></a>1，通过调用willTransition方法阻止路由转换</h3><p>当用户通过<code>{{link-to}}</code>助手、<code>transition</code>方法或者直接执行URL来转换路由，当前路由会自动执行<code>willTransition</code>方法。每个活动的路由都可以决定是否执行转换路由。</p>
<p>想象一下，在当前路由所渲染的页面是一个比较复杂的表单，并且用户已经填写了很多信息，但是用户很可能无意中点击了返回或者关闭页面，这就导致了用户填写的信息直接丢失了，这样的用户体验并不好。此时我们可以通过使用<code>willTransition</code>方法阻止用户的行为并提示用户是否确认离开本页面。</p>
<p>为了验证这个特性我们需要创建好测试所需的文件。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">ember g controller form</span><br><span class="line">ember g route form</span><br><span class="line">&#96;&#96;&#96; </span><br><span class="line">首先在&#96;controller&#96;增加测试数据。</span><br><span class="line">&#96;&#96;&#96;js</span><br><span class="line">&#x2F;&#x2F;  app&#x2F;controllers&#x2F;form.js</span><br><span class="line"></span><br><span class="line">import Ember from &#39;ember&#39;;</span><br><span class="line"></span><br><span class="line">export default Ember.Controller.extend(&#123;</span><br><span class="line">    firstName: &#39;chen&#39;,</span><br><span class="line">    lastName: &#39;ubuntuvim&#39;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>再创建一个模拟用户填写信息的模板。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">form</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;form-group&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">label</span> <span class="attr">for</span>=<span class="string">&quot;exampleInputEmail1&quot;</span>&gt;</span>FirstName<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">    &#123;&#123;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;exampleInputEmail1&quot; placeholder=&quot;FirstName&quot; value=firstName&#125;&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;form-group&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">label</span> <span class="attr">for</span>=<span class="string">&quot;exampleInputPassword1&quot;</span>&gt;</span>LashName<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">    &#123;&#123;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;exampleInputPassword1&quot; placeholder=&quot;LashName&quot; value=lastName&#125;&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span> <span class="attr">class</span>=<span class="string">&quot;btn btn-primary&quot;</span>&gt;</span>Submit<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">&#123;&#123;#link-to &#x27;about&#x27;&#125;&#125;<span class="tag">&lt;<span class="name">b</span>&gt;</span>转到about<span class="tag">&lt;/<span class="name">b</span>&gt;</span>&#123;&#123;/link-to&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>关键部分来了，我们在路由里添加<code>willTransition</code>方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/routes/form.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Route.extend(&#123;</span><br><span class="line">    actions: &#123;</span><br><span class="line">        willTransition: <span class="function"><span class="keyword">function</span>(<span class="params">transition</span>) </span>&#123;</span><br><span class="line">            <span class="comment">//  如果是使用this.get(&#x27;key&#x27;)获取不了页面输入值，因为不是通过action提交表单的</span></span><br><span class="line">            <span class="keyword">var</span> v = <span class="built_in">this</span>.controller.get(<span class="string">&#x27;firstName&#x27;</span>);</span><br><span class="line">            <span class="comment">//  任意获取一个作为判断表单输入值</span></span><br><span class="line">            <span class="keyword">if</span> (v &amp;&amp; !confirm(<span class="string">&quot;你确定要离开这个页面吗？?&quot;</span>)) &#123;</span><br><span class="line">                transition.abort();</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>运行：<a target="_blank" rel="noopener" href="http://localhost:4200/form">http://localhost:4200/form</a>，先点击<code>submit</code>提交表单，可以看到表单顺利提交没有任何问题，然后再点击<code>转到about</code>，你可以看到会弹出如下提示框。</p>
<p><img src="/content/images/2016/03/62.png" alt="run result"></p>
<p>接着，点击“取消”页面没有跳转，如果是点击“确定”页面会跳转到<code>about</code>页面。<br>再接着，把<code>FirstName</code>这个输入框的内容清空然后点击“转到about”页面直接跳转到了<code>about</code>页面。</p>
<p>很多博客网站都是有这个功能的！！</p>
<h3 id="2，在beforeModel、model、afterModel回调中阻止路由转换"><a href="#2，在beforeModel、model、afterModel回调中阻止路由转换" class="headerlink" title="2，在beforeModel、model、afterModel回调中阻止路由转换"></a>2，在beforeModel、model、afterModel回调中阻止路由转换</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">beforeModel(transition) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">new</span> <span class="built_in">Date</span>() &gt; <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">&#x27;January 1, 1980&#x27;</span>)) &#123;</span><br><span class="line">      alert(<span class="string">&#x27;Sorry, you need a time machine to enter this route.&#x27;</span>);</span><br><span class="line">      transition.abort();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这段代码演示的就是在<code>beforeModel</code>回调中使用<code>abort</code>方法阻止路由的转换。代码比较简单我就不做例子演示了！</p>
<h3 id="3，存储transition对象、路由转换重试"><a href="#3，存储transition对象、路由转换重试" class="headerlink" title="3，存储transition对象、路由转换重试"></a>3，存储transition对象、路由转换重试</h3><p>对于使用<code>abort</code>方法终止的路由可以调用<code>retry</code>方法重新激活。一个很典型的例子就是登陆。如果登陆成功就转到首页，否则跳转回登陆页面。<br>文件准备工作：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ember g controller auth</span><br><span class="line">ember g route auth</span><br><span class="line">ember g controller login</span><br><span class="line">ember g route login</span><br></pre></td></tr></table></figure>
<p>下面是演示用到的代码。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/controllers/login.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line">    actions: &#123;</span><br><span class="line">        login: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">          <span class="comment">//  获取跳转过来之前路由中设置的transition对象</span></span><br><span class="line">            <span class="keyword">var</span> transitionObj = <span class="built_in">this</span>.get(<span class="string">&#x27;transitionObj&#x27;</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;transitionObj = &#x27;</span> + transitionObj);</span><br><span class="line">            <span class="keyword">if</span> (transitionObj) &#123;</span><br><span class="line">                <span class="built_in">this</span>.set(<span class="string">&quot;transitionObj&quot;</span>, <span class="literal">null</span>);</span><br><span class="line">                transitionObj.retry();</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">//  转回首页</span></span><br><span class="line">                <span class="built_in">this</span>.transitionToRoute(<span class="string">&#x27;index&#x27;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/controllers/auth.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line">    userIsLogin: <span class="literal">false</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/routes/auth.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Route.extend(&#123;</span><br><span class="line">    beforeModel(transition) &#123;</span><br><span class="line">        <span class="comment">// 在名为auth的controller设置了userIsLogin为false，默认是未登录</span></span><br><span class="line">        <span class="keyword">if</span> (!<span class="built_in">this</span>.controllerFor(<span class="string">&quot;auth&quot;</span>).get(<span class="string">&#x27;userIsLogin&#x27;</span>)) &#123;</span><br><span class="line">            <span class="keyword">var</span> loginController = <span class="built_in">this</span>.controllerFor(<span class="string">&quot;login&quot;</span>);</span><br><span class="line">            <span class="comment">// 保存transition对象</span></span><br><span class="line">            loginController.set(<span class="string">&quot;transitionObj&quot;</span>, transition);</span><br><span class="line">            <span class="built_in">this</span>.transitionTo(<span class="string">&quot;login&quot;</span>);  <span class="comment">// 跳转到路由login</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--  //app/templates/login.hbs --&gt;</span></span><br><span class="line"></span><br><span class="line">这个是登陆页面</span><br></pre></td></tr></table></figure>

<ol>
<li>先执行<a target="_blank" rel="noopener" href="http://localhost:4200/auth">http://localhost:4200/auth</a>，然后界面会自动跳转到<code>login</code>页面，结果显示如下：</li>
</ol>
<p><img src="/content/images/2016/03/63.png" alt="result"></p>
<p>可以看到URL确实是转到<code>login</code>了。</p>
<ol start="2">
<li>执行<a target="_blank" rel="noopener" href="http://localhost:4200/login">http://localhost:4200/login</a>，你会发现页面直接跳转到首页，浏览器控制台打印的<code>transitionObj</code>是<code>undefined</code>。由于没有经<code>auth</code>这个路由的跳转所以获取不到<code>transition</code>对象。自然就跳转回<code>index</code>这个路由。</li>
</ol>
<br>
博文完整代码放在[Github](https://github.com/ubuntuvim/my_emberjs_code)（博文经过多次修改，博文上的代码与github代码可能又出入，不过影响不大！），如果你觉得博文对你有点用，请在github项目上给我点个`star`吧。您的肯定对我来说是最大的动力！！
    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/01/18/ember-teach/routing/%E8%B7%AF%E7%94%B1%E5%AE%9A%E4%B9%89/" rel="next" title="路由定义">
          路由定义
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/ember-teach/routing/%E6%A8%A1%E6%9D%BF%E6%B8%B2%E6%9F%93/" rel="prev" title="模板渲染">
            模板渲染
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%EF%BC%8C%E9%80%9A%E8%BF%87%E8%B0%83%E7%94%A8willTransition%E6%96%B9%E6%B3%95%E9%98%BB%E6%AD%A2%E8%B7%AF%E7%94%B1%E8%BD%AC%E6%8D%A2"><span class="toc-text">1，通过调用willTransition方法阻止路由转换</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%EF%BC%8C%E5%9C%A8beforeModel%E3%80%81model%E3%80%81afterModel%E5%9B%9E%E8%B0%83%E4%B8%AD%E9%98%BB%E6%AD%A2%E8%B7%AF%E7%94%B1%E8%BD%AC%E6%8D%A2"><span class="toc-text">2，在beforeModel、model、afterModel回调中阻止路由转换</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%EF%BC%8C%E5%AD%98%E5%82%A8transition%E5%AF%B9%E8%B1%A1%E3%80%81%E8%B7%AF%E7%94%B1%E8%BD%AC%E6%8D%A2%E9%87%8D%E8%AF%95"><span class="toc-text">3，存储transition对象、路由转换重试</span></a></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: '终止与重试路由跳转', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
